package com.wangsh.train.web.back.controller;

import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.wangsh.train.common.controller.BaseController;
import com.wangsh.train.common.pojo.ApiResponse;
import com.wangsh.train.common.pojo.ApiResponseEnum;
import com.wangsh.train.common.util.ConstatFinalUtil;
import com.wangsh.train.common.util.PageInfoUtil;
import com.wangsh.train.outer.IClientOuterService;
import com.wangsh.train.users.pojo.AAdmins;
import com.wangsh.train.users.service.IUsersDbService;

/**
 * 	管理员后台Controller
 * 	@author wangsh
 */
@Controller
@RequestMapping("/back/admins/")
public class AdminsBackController extends BaseController
{
	@Resource
	private IUsersDbService usersDbService;
	@Resource
	private IClientOuterService clientOuterService;
	
	/**
	 * 首页
	 * @return
	 */
	@RequestMapping("/main")
	public String main()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--main--");
		return "/back/admins/main";
	}
	
	/**
	 * 欢迎页面
	 * @return
	 */
	@RequestMapping("/welcome")
	public String welcome()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--welcome--");
		return "/back/admins/welcome";
	}
	
	/**
	 * 管理员列表页面
	 * @return
	 */
	@RequestMapping("/adminsList")
	public String adminsList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--adminsList--");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<AAdmins> response = this.usersDbService.findCondListAdminsService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/back/admins/adminsList";
	}
	
	/**
	 * 打开管理员更新页面
	 * @return
	 */
	@RequestMapping("/adminsUpdate")
	public String adminsUpdate(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--adminsUpdate--");
		/* 从session中获取信息 */
		String id = request.getParameter("id");
		/* 准备请求的信息 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		ApiResponse<AAdmins> apiResponse = this.usersDbService.findOneAdminsService(condMap);
		model.addAttribute("response", apiResponse.toJSON());
		
		String operType = request.getParameter("operType");
		request.setAttribute("operType", operType);
		return "/back/admins/adminsInfo";
	}
	
	/**
	 * 更新管理员信息
	 */
	@RequestMapping(value = "/adminsUpdateSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String adminsUpdateSubmit(HttpServletRequest request,Model model)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 从session中获取信息 */
		String id = request.getParameter("id");
		AAdmins adminsSess = (AAdmins) this.findObjfromSession(request, "admins");
		/* 只处理当前用户的信息 */
		String self = request.getParameter("self");
		if("true".equalsIgnoreCase(self))
		{
			id = adminsSess.getId() + ""; 
		}
		/* 准备请求的信息 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		ApiResponse<AAdmins> apiResponseRes = this.usersDbService.findOneAdminsService(condMap);
		model.addAttribute("response", apiResponseRes.toJSON());
		
		AAdmins admins = apiResponseRes.getDataOneJava() ; 
		
		boolean flag = false ; 
		String operType = request.getParameter("operType");
		if("updateSyna".equalsIgnoreCase(operType))
		{
			JSONObject dataReqJSON = new JSONObject();
			dataReqJSON.put("token", adminsSess.getTokenStr());
			
			/* 验证管理员的token */
			JSONObject responseJSON = this.clientOuterService.verifyAdminsTokenService(dataReqJSON);
			if(responseJSON != null && responseJSON.getInteger("code") == ApiResponseEnum.STATUS_SUCCESS.getStatus())
			{
				//登陆成功
				JSONObject dataJSON = (JSONObject) responseJSON.get("data");
				JSONObject adminsJSON = dataJSON.getJSONObject("admins");
				String email = adminsJSON.get("email") + "";
				String name = adminsJSON.get("name") + "";
				String lastLoginTime = adminsJSON.get("lastLoginTime") + "";
				
				admins.setEmail(email);
				admins.setName(name);
				admins.setSsoId(Integer.valueOf(id));
				admins.setUpdateTime(new Date());
				admins.setLastLoginTime(this.dateFormatUtil.strDateTime(lastLoginTime));
				flag = true ; 	
			}
		}
		
		if(flag)
		{
			/* 更新用户信息 */
			apiResponse = this.usersDbService.updateOneAdminsService(admins);
		}
		return apiResponse.toJSON().toJSONString() ; 
	}
	
	/**
	 * 退出页面
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response , HttpSession session)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--logout--");
		String returnUrl = request.getParameter("returnUrl");
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 获取用户 */
		AAdmins admins = (AAdmins) this.findObjfromSession(request, "admins");
		if(returnUrl == null)
		{
			returnUrl = "" ; 
		}
		try
		{
			returnUrl = URLEncoder.encode(returnUrl, "UTF-8");
			/* 做一些清除的操作 */
			session.removeAttribute("admins");
			session.removeAttribute("lastLoginTime");
			
			apiResponse.setCode(ApiResponseEnum.INFO_LOGOUT.getStatus()); 
			/* 客户端跳转到登陆页面 */
			String logoutUrl = ConstatFinalUtil.CONFIG_JSON.getString("usersCenter.back.logout.url");
			logoutUrl += "&returnUrl=" + URLEncoder.encode(returnUrl,"UTF-8") ; 
			response.sendRedirect(logoutUrl);
			return null ; 
		} catch (Exception e)
		{
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus()); 
			ConstatFinalUtil.SYS_LOGGER.error("退出报错了;email:{}", admins.getEmail(),e);
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		/* 提示信息 */
		session.setAttribute("response", apiResponse.toJSON());
		return null ; 
	}
}
